package com.example.gkcircle.fragment.lost;

import android.content.Intent;
import android.net.Uri;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.example.gkcircle.App;
import com.example.gkcircle.BaseFragment;
import com.example.gkcircle.R;
import com.example.gkcircle.activity.LostAndFoundActivity;
import com.example.gkcircle.activity.SearchLostActivity;
import com.example.gkcircle.adapter.LostAdapter;
import com.example.gkcircle.bean.Lost;
import com.example.gkcircle.utils.ActivityUtil;
import com.example.gkcircle.utils.DateUtil;
import com.example.gkcircle.utils.MyAlertView;
import com.example.gkcircle.utils.ToastFactory;
import java.util.ArrayList;
import java.util.List;


/**
 * 招领Fragment
 * @author ZhouHua
 * created at 15/12/21 上午12:57
 */
public class FoundFragment extends BaseFragment implements AbsListView.OnScrollListener{

    private ListView mListView;
    private LostAdapter mAdapter;
    private View mHeaderView;
    private SwipeRefreshLayout mSwipe;
    private static FoundFragment instance;

    private int currentPage=0;
    private final int maxDataCount=10;
    private boolean isRefreshing;

    private FoundFragment() {
    }

    public static FoundFragment getInstance() {
        if (instance == null) instance = new FoundFragment();
        return instance;
    }

    @Override
    protected int setLayout() {
        return R.layout.home_found_fragment;
    }

    @Override
    protected void initView(View view) {
        mListView=(ListView)view.findViewById(R.id.found_listview);
        mSwipe=(SwipeRefreshLayout)view.findViewById(R.id.found_swipe);
        mSwipe.setColorSchemeColors(getResources().getColor(R.color.main), getResources().getColor(R.color.love), getResources().getColor(R.color.wish));

        if(mHeaderView==null){
            mHeaderView=LayoutInflater.from(getActivity()).inflate(R.layout.home_lost_header,null,false);
            //搜索点击事件
            mHeaderView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivityUtil.startActivity(getActivity(), SearchLostActivity.class);

                }
            });
            mListView.addHeaderView(mHeaderView);
        }

        //发布回调
        setActivityResult(new IActivityResultListener() {
            @Override
            public void complete() {
                if(!isRefreshing){
                    isRefreshing=true;
                    currentPage = 0;
                    setData();
                }
            }
        });

        //拨打电话回调显示AlertView
        FoundFragment.onShowAlertViewListener=new OnShowAlertViewListener() {
            @Override
            public void show(final String telNumber) {
                MyAlertView.showAlertViewWithOKAndCancel(getActivity(), "是否拨打  " + telNumber, new MyAlertView.IShowAlertViewWithOkAndCancelListener() {
                    @Override
                    public void onclickOk() {
                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + telNumber));
                        getActivity().startActivity(intent);
                    }
                });
                MyAlertView.alertView=null;
            }
        };
    }

    @Override
    protected void initListener() {
        currentPage=0;
        mListView.setOnScrollListener(this);
        //下拉刷新
        mSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if(!isRefreshing){
                    isRefreshing=true;
                    currentPage = 0;
                    setData();
                }
            }
        });
    }

    //上拉加载
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        switch (scrollState){
            case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                if(mListView.getLastVisiblePosition()==(mListView.getCount()-1)){
                    currentPage++;
                    setData();
                }
                break;
        }
    }


    @Override
    protected void setData() {
        mSwipe.setRefreshing(true);
        getData(currentPage, new IGetDataListener() {
            @Override
            public void complete(List<AVObject> list) {
                if(list==null){
                    currentPage--;
                    return;
                }
                if(App.mFoundList==null){
                    App.mFoundList=new ArrayList<Lost>();
                }else{
                    if(isRefreshing)App.mFoundList.clear();
                }
                for (int i = 0; i < list.size(); i++) {
                    Lost lost = new Lost();
                    lost.setUser(list.get(i).getAVUser("user"));
                    lost.setContacts(list.get(i).get("contacts").toString());
                    lost.setContent(list.get(i).get("content").toString());
                    lost.setCreatedAt(DateUtil.getLastMinTime(list.get(i).getDate("createdAt").getTime()));
                    lost.setPhotoUrl(list.get(i).getAVFile("photo") == null ? null : list.get(i).getAVFile("photo").getUrl());
                    App.mFoundList.add(lost);
                }
                if (mAdapter != null) {
                    mAdapter.notifyDataSetChanged();
                    mSwipe.setRefreshing(false);
                    return;
                }
                mSwipe.setRefreshing(false);
                mAdapter=new LostAdapter(getActivity(),App.mFoundList,LostAdapter.FOUND_FLAG);
                mListView.setAdapter(mAdapter);
            }
        });
    }

    //获取数据
    public IGetDataListener getDataListener;

    private interface IGetDataListener{
        void complete(List<AVObject> list);
    }

    private void getData(final int currentPage,final IGetDataListener getDataListener){
        this.getDataListener=getDataListener;

        AVQuery<AVObject> query=new AVQuery<>("Found");
        query.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
        query.setLimit(maxDataCount);
        query.setSkip(maxDataCount * currentPage);
        query.orderByDescending("createdAt");
        query.include("user");

        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (e == null) {
                    if (list.size() > 0) {
                        if(dataFlag)getDataListener.complete(list);else return;
                    } else {
                        if(dataFlag)getDataListener.complete(null);else return;
                        mSwipe.setRefreshing(false);
                        ToastFactory.getToast(getActivity(), getResources().getString(R.string.no_more_data)).show();
                    }
                } else {
                    mSwipe.setRefreshing(false);
                    ToastFactory.getToast(getActivity(), getResources().getString(R.string.connection_error)).show();
                }
            }
        });
    }

    //拨打电话回调
    public static OnShowAlertViewListener onShowAlertViewListener;

    public interface OnShowAlertViewListener{
        void show(String telNumber);
    }

    //发布回调接口
    public static IActivityResultListener iActivityResultListener;

    public interface IActivityResultListener{
        void complete();
    }
    public  void setActivityResult(IActivityResultListener iActivityResultListener){
        this.iActivityResultListener=iActivityResultListener;
    }


    //隐藏浮动菜单
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (LostAndFoundActivity.mFloatingActionButton != null) {
            if (LostAndFoundActivity.firstVisibleItem > firstVisibleItem) {
                LostAndFoundActivity.firstVisibleItem = firstVisibleItem;
            }
            if (LostAndFoundActivity.firstVisibleItem == firstVisibleItem) {
                LostAndFoundActivity.mFloatingActionButton.setVisibility(View.VISIBLE);
            } else {
                LostAndFoundActivity.mFloatingActionButton.setVisibility(View.GONE);
                LostAndFoundActivity.firstVisibleItem = firstVisibleItem == 0 ? 0 : firstVisibleItem - 1;
                if (LostAndFoundActivity.mFloatingActionMenu.isOpen()) {
                    LostAndFoundActivity.mFloatingActionMenu.close(true);
                }
            }
        }
    }



    @Override
    public void onPause() {
        mSwipe.setRefreshing(false);
        super.onPause();
    }
}
